package com.audaque.springboot.foshanupload.web.nosaveframeworklogin.interceptor;


import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//通过配置order()的值，值越小，优先级越高。不配默认是0
@Order(100)
public class LoginResponseInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TransmittableThreadLocalCurrentUser current = TransmittableThreadLocalCurrentUser.getCurrentUser();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");


        if(current!=null){
            R r = R.ok();
            r.setData(current);
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return true;
        }else{
            R r = new R();
            r.setSuccess(false);
            r.setCode(ResultCodeEnum.LOGIN_FAILE.getCode());
            r.setMsg(ResultCodeEnum.LOGIN_FAILE.getMsg());
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return false;
        }

    }
}
